/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.satyam.swingvalidator.commons;

import com.satyam.swingvalidator.core.AbstractValidator;
import com.satyam.swingvalidator.core.Severity;
import javax.swing.JComponent;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

/**
 *
 * @author Satyam
 */
public class MaxLengthValidator extends AbstractValidator {

    private final int maxLength;

    public MaxLengthValidator(int maxLength) {
        this.maxLength = maxLength;
    }

    @Override
    protected Severity getValidationCriteria(JComponent c) {
        String strToVerfify = "";
        if (c instanceof JTextField) {
            strToVerfify = ((JTextField) c).getText();
        } else if (c instanceof JPasswordField) {
            strToVerfify = new String(((JPasswordField) c).getPassword());
        }
        boolean result = strToVerfify.length() <= maxLength;

        if (strToVerfify.trim().length() == 0) {
            return new Severity(Severity.ERROR, "This field cannot be empty!");
        }
        if (result) {
            return new Severity(Severity.NO_ERROR, "");
        } else {
            return new Severity(Severity.ERROR, "The maximum size of this field is " + maxLength);
        }
    }

}
